package ai

import (
	"chatgpt/ai/chatglm"
	"chatgpt/ai/models"
	openai2 "chatgpt/ai/openai"
	"chatgpt/ai/zhipu"
	"chatgpt/helper"
	"chatgpt/helper/code"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func Completion(ctx *gin.Context, quest string, m map[string]string, call func() string) (code.CODENO, *helper.ResponseDesc) {
	var w http.ResponseWriter
	if val, ok := m["stream"]; ok && (val != "") {
		w = ctx.Writer
	}
	switch strings.ToLower(models.GetCompanyWithModel(m["smodel"])) {
	case openai2.CONST_COMPANY:
		if call != nil {
			quest = call()
		}
		//quest, _ = openai2.CustomQuestion(quest)
		mm := helper.ConvMapStringToMapAny(m)
		mm["q"] = quest
		mcode, replay := openai2.CompletionRemote(w, mm)
		return mcode, &helper.ResponseDesc{
			MsgCode: (replay.MsgCode),
			Data:    replay.Data,
			Tokens:  replay.Tokens,
			Desc:    replay.Desc,
		}

	case chatglm.CONST_COMPANY:
		key_word := quest
		quest, _ = chatglm.Search.CustomQuestion(quest)
		act_m := map[string]string{
			"key_word": key_word,
			"prompt":   quest,
			"stream":   m["stream"],
		}
		mcode, replay := chatglm.CompletionRemote(w, chatglm.GLM_COMPLETION, quest, act_m)
		return mcode, &helper.ResponseDesc{
			MsgCode: (replay.MsgCode),
			Data:    replay.Data,
			Tokens:  replay.Tokens,
			Desc:    replay.Desc,
		}
	case zhipu.CONST_COMPANY:
		key_word := quest
		quest, _ = zhipu.Search.CustomQuestion(quest)
		act_m := map[string]string{
			"key_word": key_word,
			"prompt":   quest,
			"stream":   m["stream"],
			"smodel":   m["smodel"],
		}
		mcode, replay := zhipu.CompletionRemote(w, zhipu.GLM_COMPLETION, quest, act_m)
		return mcode, &helper.ResponseDesc{
			MsgCode: (replay.MsgCode),
			Data:    replay.Data,
			Tokens:  replay.Tokens,
			Desc:    replay.Desc,
		}
	}

	return code.SUCCESS, nil
}

func StreamCheck(stream_any any) bool {
	switch val := stream_any.(type) {
	case bool:
		return val
	case string:
		if val != "" && val != "false" {
			return true
		}
	}
	return false
}
